package com.sskj.fabi.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.sskj.common.base.App;
import com.sskj.common.base.HttpData;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.box.inputfilter.MoneyValueFilter;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;
import com.sskj.fabi.bean.FBPrice;
import com.sskj.fabi.bean.FaBiDialogBean;
import com.sskj.fabi.bean.PayWayBean;
import com.sskj.fabi.bean.TabEntity;
import com.sskj.fabi.presenter.FabiPublishPresenter;
import com.sskj.fabi.util.TipFabiUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.adapter.BaseAdapter;
import com.sskj.lib.adapter.ViewHolder;
import com.sskj.lib.base.BaseActivity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;

/**
 * 发布页面
 */
public class FabiPublishActivity extends BaseActivity<FabiPublishPresenter> {
    @BindView(R2.id.commonTabLayout)
    CommonTabLayout commonTabLayout;
    @BindView(R2.id.bt_control)
    Button mBtControl;  // 出售按钮
    @BindView(R2.id.iv_back)
    ImageView ivBack;
    @BindView(R2.id.iv_right)
    ImageView ivRight;  // 右侧图标---点击进入求购/出售列表
    @BindView(R2.id.pay_way_recyclerview)
    RecyclerView mPayWayRecyclerview;
    @BindView(R2.id.fabi_publish_count)
    EditText mFabiPublishCount;
    @BindView(R2.id.fabi_publish_input_low)
    EditText mFabiPublishInputLow;
    @BindView(R2.id.fabi_publish_input_hight)
    EditText mFabiPublishInputHight;
    @BindView(R2.id.fabi_publish_input_unit_price)
    EditText mFabiPublishInputUnitPrice;  // 单价
    @BindView(R2.id.fabi_publish_input_remark)
    EditText mFabiPublishInputRemark;
    @BindView(R2.id.publish_title)
    TextView publishTitle;
    //    @BindView(R.id.remark_layout)
//    LinearLayout mRemarkLayout;
    private String[] mTitles = {"发布出售", "发布购买"};
    private BaseAdapter<PayWayBean> mBaseAdapter;
    private ArrayList<CustomTabEntity> mTabEntities;
    private View mFooterView;
    private int mPayWx = 0;
    private int mPayAli = 0;
    private int mPayBank = 0;
    private int mPaypal = 0;
    private String ckPrice;
    private boolean isBuy = false; // true购买   false 出售
    /**
     * 发布类型 0：出售，  or 求购
     */
    private int mIndex = 0;
    private int typeNumEditFilter = 4;  //数量小数点位
    private int typePriceEditFilter = 2;//价格小数点位


    @Override
    protected int getLayoutResId() {
        return R.layout.fabi_activity_fabi_publish;
    }

    @Override
    public FabiPublishPresenter getPresenter() {
        return new FabiPublishPresenter();
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, FabiPublishActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        super.initView();
        mFabiPublishCount.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(typeNumEditFilter)});
        mFabiPublishInputLow.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(typePriceEditFilter)});
        mFabiPublishInputHight.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(typePriceEditFilter)});
        ClickUtil.click(ivRight, () -> {  // 发布出售、购买记录
            FabiPublishRecordActivity.start(FabiPublishActivity.this);
        });
        ClickUtil.click(ivBack, () -> {
            finish();
        });
        mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }
        commonTabLayout.setTabData(mTabEntities);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mIndex = position;
                publishTitle.setText(position == 0 ? "商家自由出售BDD,交易更灵活便捷" : "商家自由购买BDD,交易更灵活便捷");
                mBtControl.setText(position == 0 ? "出售" : "购买");
                mFabiPublishCount.setHint(position == 0 ? "发布出售数量" : "发布购买数量");
                mFabiPublishCount.setText("");
                mFabiPublishInputUnitPrice.setHint(position == 0 ? "请输入出售单价" : "请输入购买单价");
                switch (position) {
                    case 0:
                        isBuy = false;
                        break;
                    case 1:
                        isBuy = true;
                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        ClickUtil.click(mBtControl, () -> {
            String fabuNum = mFabiPublishCount.getText().toString().trim();
            String minPrice = mFabiPublishInputLow.getText().toString().trim();
            String maxPrice = mFabiPublishInputHight.getText().toString().trim();
            String notes = mFabiPublishInputRemark.getText().toString().trim();
            if (TextUtils.isEmpty(ckPrice)) {
                ToastUtil.showShort("请刷新页面获取单价");
                return;
            }
            if (TextUtils.isEmpty(fabuNum)) {
                ToastUtil.showShort("请输入发布数量");
                return;
            }
            if (TextUtils.isEmpty(minPrice)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabiMerchantOrderBuyFragment45));
                return;
            }
            if (Double.valueOf(minPrice) <= 0) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabiMerchantOrderBuyFragment46));
                return;
            }
            if (TextUtils.isEmpty(maxPrice)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabiMerchantOrderBuyFragment47));
                return;
            }
            double money = Double.valueOf(ckPrice) * Double.valueOf(fabuNum);
            if (Double.valueOf(maxPrice) < Double.valueOf(minPrice)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabiMerchantOrderBuyFragment48));
                return;
            }
            if (Double.valueOf(maxPrice) > Double.valueOf(money)) {
                ToastUtil.showShort(App.INSTANCE.getString(R.string.fabiMerchantOrderBuyFragment49) + NumberUtil.keep2Down(money));
                return;
            }
            if (mPayAli == 0 && mPayWx == 0 && mPayBank == 0 && mPaypal == 0) {
                ToastUtil.showShort("请选择支付方式");
                return;
            }
            FaBiDialogBean faBiDialogBean = new FaBiDialogBean(ckPrice, fabuNum, NumberUtil.keep2(String.valueOf(money)));
            TipFabiUtil.customTip1(this, isBuy, faBiDialogBean, new TipFabiUtil.OnTipSure() {
                @Override
                public void onSure(String payPwd) {
                    mPresenter.requsetPublish(fabuNum, minPrice, maxPrice, isBuy ? "pmma" : "sell", mPayWx, mPayAli, mPayBank, mPaypal, notes, payPwd);
                }
            }).show();
        });
//        mPayWayRecyclerview.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        mPayWayRecyclerview.addItemDecoration(new DividerLineItemDecoration(this)
                .setLastDraw(false)
                .setFirstDraw(false)
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.fabi_backgroud))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 2)));
        mPayWayRecyclerview.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mBaseAdapter = new BaseAdapter<PayWayBean>(R.layout.fabi_recy_item_pay_way, null, mPayWayRecyclerview) {
            @Override
            public void bind(ViewHolder holder, PayWayBean item) {
                holder.setText(R.id.item_checkbox, item.getTip());
                if ("wx".equals(item.getType())) {
                    mPayWx = 1;
                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(R.mipmap.fabi_wechat, 0, R.drawable.selector_checkbox, 0);
                } else if ("alipay".equals(item.getType())) {
                    mPayAli = 1;
                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(R.mipmap.fabi_alipay, 0, R.drawable.selector_checkbox, 0);
                } else if ("backcard".equals(item.getType())) {
                    mPayBank = 1;
                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(R.mipmap.fabi_bank, 0, R.drawable.selector_checkbox, 0);
                } else if ("paypal".equals(item.getType())) {
                    mPaypal = 1;
                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(R.mipmap.fabi_paypal, 0, R.drawable.selector_checkbox, 0);
                }
                holder.setOnCheckedChangeListener(R.id.item_checkbox, new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            if ("wx".equals(item.getType())) {
                                mPayWx = 1;
                            } else if ("alipay".equals(item.getType())) {
                                mPayAli = 1;
                            } else if ("backcard".equals(item.getType())) {
                                mPayBank = 1;
                            } else if ("paypal".equals(item.getType())) {
                                mPaypal = 1;
                            }
                        } else {
                            if ("wx".equals(item.getType())) {
                                mPayWx = 0;
                            } else if ("alipay".equals(item.getType())) {
                                mPayAli = 0;
                            } else if ("backcard".equals(item.getType())) {
                                mPayBank = 0;
                            } else if ("paypal".equals(item.getType())) {
                                mPaypal = 0;
                            }
                        }
                    }
                });
            }
        };
        mFooterView = LayoutInflater.from(this).inflate(R.layout.fabi_item_text, null);
        mFooterView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build(RConfig.MINE_SECURITY_CENTER).navigation();
            }
        });
        mBaseAdapter.setFooterView(mFooterView);
    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.getFbPrice();
        mPresenter.requsetPayWayList();
    }

    /**
     * 支付方式
     */
    public void onPayWaySuccess(HttpData<List<PayWayBean>> body) {
        //使用java.util.Iterator
        for (Iterator it = body.getData().iterator(); it.hasNext(); ) {
            PayWayBean obj = (PayWayBean) it.next();
            if (obj.getStatus() == 0) {
                it.remove();
            }
        }
        if (body.getData().size() < 4) {
            if (mBaseAdapter.getFooterLayoutCount() == 0) {
                mBaseAdapter.addFooterView(mFooterView);
            }
        }
        mBaseAdapter.setNewData(body.getData());
    }

    public void setData(FBPrice fbPrice) {
        ckPrice = fbPrice.getFb_price();
        mFabiPublishInputUnitPrice.setText(TextUtils.isEmpty(ckPrice) ? "" : ckPrice);
    }

    //商家发布成功，清空EditText
    public void updateUi() {
        finish();
    }
}
